package persistence.sale;

import java.sql.*;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Sale;

public class SaleDAOJDBC implements SaleDAO {

    private final Object lockOfTheConexion = new Object();
    private Connection conexion = null;
    private static SaleDAOJDBC persistenceManager = null;
    private static final Logger logger = Logger.getLogger(SaleDAOJDBC.class.getName());

    SaleDAOJDBC() {
    }

    public static SaleDAOJDBC getJDBCPersistenceManager() {
        if (persistenceManager == null) {
            persistenceManager = new SaleDAOJDBC();
        }
        return persistenceManager;
    }

    @Override
    public boolean setUp(String url, String driver, String user, String password) {
        try {
            Class.forName(driver);
            conexion = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException ex) {
            logger.log(Level.SEVERE, "No se encontro el driver para la base de datos", ex);
            return false;
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, "No se pudo establecer la conexion con la base de datos", ex);
            return false;
        }
        return true;
    }

    @Override
    public boolean disconnect() {
        try {
            conexion.close();
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, "Conexi�n a la base de datos no cerrada", ex);
            return false;
        }
        return true;
    }

    @Override
    public boolean createSale(Sale sale) {
        String query = "insert into\"VENTAS\" values(?,?,?,?,?,?,?)";
        PreparedStatement statement;
        try {
            synchronized (lockOfTheConexion) {
                statement = conexion.prepareStatement(query);
            }
            statement.setString(1, sale.getId());
            statement.setString(2, sale.getProductos());
            statement.setString(3, sale.getUsuario());
            statement.setFloat(4, sale.getImporte());
            statement.setString(5, sale.getPago());
            statement.setString(6, sale.getDireccion());
            statement.setString(7, sale.getFecha());
            statement.execute();
            return true;
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, "Error al crear una venta", ex);
            return false;
        }
    }

    @Override
    public void readAllSales(Map<String, Sale> saleArray) {
        String query = "select * from \"VENTAS\"";
        PreparedStatement statement;
        ResultSet resultSet = null;
        Sale sale = new Sale();
        try {
            synchronized (lockOfTheConexion) {
                statement = conexion.prepareStatement(query);
            }
            resultSet = statement.executeQuery();
            for (int i = 0; resultSet.next(); i++) {
                sale = new Sale();
                sale.setId(resultSet.getString("ID"));
                sale.setProductos(resultSet.getString("PRODUCTO"));
                sale.setUsuario(resultSet.getString("USUARIO"));
                sale.setImporte(resultSet.getFloat("IMPORTE"));
                sale.setPago(resultSet.getString("PAGO"));
                sale.setDireccion(resultSet.getString("DIRECCION"));
                sale.setFecha(resultSet.getString("FECHA"));
                saleArray.put(sale.getId(), sale);
            }
        } catch (SQLException ex) {
            logger.log(Level.SEVERE, "Error al leer una venta", ex);
        }
    }

    public void setConnection(Connection conexion) {
        synchronized (lockOfTheConexion) {
            this.conexion = conexion;
        }
    }
}
